from typing import List

from django.shortcuts import get_object_or_404
from ninja import Router
from ninja.pagination import paginate

from django_starter.http.response import responses

from apps.{{ app.name }}.models import *
from apps.{{ app.name }}.apis.{{ model.slug }}.schemas import *

router = Router(tags=['{{ model.slug }}'])


@router.post('/', response={{ model.name }}Out, url_name='{{ app.name }}/{{ model.slug }}/create')
def create(request, payload: {{ model.name }}In):
    item = {{ model.name }}.objects.create(**payload.dict())
    return item


@router.get('/{item_id}', response={{ model.name }}Out, url_name='{{ app.name }}/{{ model.slug }}/retrieve')
def retrieve(request, item_id):
    item = get_object_or_404({{ model.name }}, id=item_id)
    return item


@router.get('/', response=List[{{ model.name }}Out], url_name='{{ app.name }}/{{ model.slug }}/list')
@paginate
def list_items(request):
    qs = {{ model.name }}.objects.all()
    return qs


@router.put('/{item_id}', response={{ model.name }}Out, url_name='{{ app.name }}/{{ model.slug }}/update')
def update(request, item_id, payload: {{ model.name }}In):
    item = get_object_or_404({{ model.name }}, id=item_id)
    for attr, value in payload.dict().items():
        setattr(item, attr, value)
    item.save()
    return item


@router.patch('/{item_id}', response={{ model.name }}Out, url_name='{{ app.name }}/{{ model.slug }}/partial_update')
def partial_update(request, item_id, payload: {{ model.name }}In):
    item = get_object_or_404({{ model.name }}, id=item_id)
    for attr, value in payload.dict(exclude_unset=True).items():
        setattr(item, attr, value)
    item.save()
    return item


@router.delete('/{item_id}', url_name='{{ app.name }}/{{ model.slug }}/destroy')
def destroy(request, item_id):
    item = get_object_or_404({{ model.name }}, id=item_id)
    item.delete()
    return responses.ok('已删除')
